import 'package:dio/dio.dart';
import '../models/collect_list_item.dart';
import '../models/response.dart'; // 假设您的 ResponseSuccess 模型在这里
import 'dio_client.dart';       // 假设您的 Dio 客户端配置在这里

class CollectAPI {
  final Dio _dio = DioClient().dio;

  /// 收藏一个帖子
  /// (此函数无需修改)
  Future<ResponseSuccess<void>> collectPost(String postId) async {
    try {
      final response = await _dio.post('/collect/$postId');
      return ResponseSuccess.fromJson(response.data, (_) => null);
    } on DioException catch (e) {
      final errorMessage = e.response?.data?['msg'] ?? '收藏帖子失败';
      throw 'Error: $errorMessage (Status: ${e.response?.statusCode})';
    } catch (e) {
      print('collectPost unknown error: $e');
      throw '收藏帖子发生未知错误: $e';
    }
  }

  /// 取消收藏一个帖子
  /// (此函数无需修改)
  Future<ResponseSuccess<void>> uncollectPost(String postId) async {
    try {
      final response = await _dio.delete('/uncollected/$postId');
      return ResponseSuccess.fromJson(response.data, (_) => null);
    } on DioException catch (e) {
      final errorMessage = e.response?.data?['msg'] ?? '取消收藏失败';
      throw 'Error: $errorMessage (Status: ${e.response?.statusCode})';
    } catch (e) {
      print('uncollectPost unknown error: $e');
      throw '取消收藏发生未知错误: $e';
    }
  }

  /// 切换指定帖子的收藏状态 (收藏/取消收藏)
  ///
  /// 对应后端路由: POST /toggle_collect/:post_id
  ///
  /// [postId] 帖子的ID
  /// 返回操作后帖子的最终收藏状态 `true` (已收藏) 或 `false` (未收藏)
  Future<ResponseSuccess<bool>> toggleCollect(String postId) async {
    try {
      final response = await _dio.post('/toggle_collect/$postId');

      // *** 修改点 ***
      // 根据新的数据结构，'data' 字段直接就是布尔值
      return ResponseSuccess.fromJson(response.data, (json) {
        // 'json' 参数现在就是 data 字段的值，即 true 或 false
        return json as bool? ?? false;
      });
    } on DioException catch (e) {
      final errorMessage = e.response?.data?['msg'] ?? '切换收藏状态失败';
      throw 'Error: $errorMessage (Status: ${e.response?.statusCode})';
    } catch (e) {
      print('toggleCollect unknown error: $e');
      throw '切换收藏状态发生未知错误: $e';
    }
  }

  /// 获取当前用户对指定帖子的收藏状态
  ///
  /// 对应后端路由: GET /collect_status/:post_id
  ///
  /// [postId] 帖子的ID
  /// 返回 `true` 如果已收藏, `false` 如果未收藏
  Future<ResponseSuccess<bool>> getCollectStatus(String postId) async {
    try {
      final response = await _dio.get('/collect_status/$postId');

      // *** 修改点 ***
      // 假设此接口与 toggle_collect 返回相同的 data 结构
      return ResponseSuccess.fromJson(response.data, (json) {
        // 'json' 参数就是 data 字段的值，即 true 或 false
        return json as bool? ?? false;
      });
    } on DioException catch (e) {
      final errorMessage = e.response?.data?['msg'] ?? '获取收藏状态失败';
      throw 'Error: $errorMessage (Status: ${e.response?.statusCode})';
    } catch (e) {
      print('getCollectStatus unknown error: $e');
      throw '获取收藏状态发生未知错误: $e';
    }
  }

  Future<ResponseSuccess<List<CollectListItem>>> getCollections({
    int page = 1,
    int size = 10,
  }) async {
    try {
      // 发送GET请求
      final response = await _dio.get(
        '/collections',
        // queryParameters: {
        //   'page': page,
        //   'size': size,
        // },
        // },
      );

      // 解析响应
      return ResponseSuccess.fromJson(
        response.data,
            (json) {
          // 将data字段转换为CollectListItem列表
          if (json is List) {
            return json
                .map((item) => CollectListItem.fromJson(item as Map<String, dynamic>))
                .toList();
          }
          return []; // 返回空列表避免null
        },
      );
    } on DioException catch (e) {
      // 处理Dio错误
      final errorMsg = e.response?.data?['msg'] ?? '获取收藏列表失败';
      throw Exception('$errorMsg (Status: ${e.response?.statusCode})');
    } catch (e) {
      // 处理其他未知错误
      print('getCollections未知错误: $e');
      throw Exception('获取收藏列表时发生未知错误: $e');
    }
  }

}